import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { PrimaryGhostC, DATA_ENTRY, AdvancedSearch, ContentPackage } from '../../../comps';
import myStyle from './index.less';
import CalendarC from './CalendarC';
import { getMonthFirstDay } from '../../../utils/utils';

moment.locale('zh-cn');
const dateFormat = 'YYYY-MM-DD';

@connect(({ SystemCalendarM, loading }) => ({
  SystemCalendarM,
  loading,
}))
@Form.create()
export default class SystemCalendarC extends PureComponent {
  state = {
    currentDate: moment().format('YYYY-MM-DD'), //选中的当前日期
    currentTime: new Date().getTime(),
  };

  componentDidMount() {}
  componentWillUnmount() {
    // 离开前清除models数据
  }
  //选择了哪一天 调用方法
  handleSelectedDate = (e) => {
    this.setState({
      currentDate: e.format(dateFormat),
    });
    //如果新选中月份 与原来的年月不一致 则更新时间戳 重新请求数据
    if (moment(this.state.currentDate).format('YYYY-MM') != moment(e).format('YYYY-MM')) {
      this.setState({
        currentTime: new Date().getTime(),
      });
    }
    //变更date表单值 年月不同 则变更
    if (e.format('YYYY-MM') != this.childSearch.props.form.getFieldsValue().date.format('YYYY-MM')) {
      this.childSearch.props.form.setFieldsValue({
        date: e,
      });
    }
  };
  //点击今天
  handleToday = () => {
    this.childSearch.handleReset(); //重置搜索条件
    this.setState({
      currentDate: moment().format('YYYY-MM-DD'),
    });
    //如果选中月份 不是今天所在的月份 则更新时间戳 重新请求数据
    if (moment().format('YYYY-MM') != moment(this.state.currentDate).format('YYYY-MM')) {
      this.setState({
        currentTime: new Date().getTime(),
      });
    }
  };

  render() {
    const { currentTime, currentDate } = this.state;
    const searchProps = {
      selfButt: <PrimaryGhostC title='今天' style={{ marginLeft: '16px', borderRadius: '2px' }} onClick={this.handleToday} />,
      allowClear: false,
      dataSource: [
        {
          dataIndex: 'date',
          title: '月份选择',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(),
          dataType: 'month',
          allowClear: false,
        },
      ],
      onQuery: (e) => {
        const date = getMonthFirstDay(e.date);
        this.setState({
          currentDate: date.format('YYYY-MM-DD'),
          currentTime: new Date().getTime(),
        });
      },
      onRef: (ref) => {
        this.childSearch = ref;
      },
    };
    return (
      <ContentPackage
        title='日历管理'
        contentHtml={
          <div className={myStyle.SystemCalendar}>
            <div className={myStyle.cardBody}>
              <AdvancedSearch {...searchProps} />
            </div>
            {/* 日历部分 */}
            <CalendarC onSelect={this.handleSelectedDate} date={currentDate} currentTime={currentTime} />
          </div>
        }
      />
    );
  }
}
